# _*_ coding:utf-8 _*_

#@Time :2020/8/23 

# @Author : litao

# @File : models.py

import time, uuid
from utils.LoggerUtil import logger
from app.orm import select, execute, Model, StringField, TextField, IntegerField
from urllib.parse import quote
# from VO.ProjectVO import ProjectVO
# from VO.ProductVO import ProductVO
from utils.MyUtil import MyUtil
class Project(Model):
    __table__ = 'quickdraw_software_project'
    id = IntegerField(primary_key=True)
    qdsoftid = StringField(name='工厂id', ddl='varchar(255)')
    userid = StringField(ddl='varchar(255)')
    guid = StringField(ddl='varchar(255)')
    sNo = StringField(ddl='varchar(255)')
    sName = StringField(ddl='varchar(255)')
    sDes = StringField(ddl='varchar(255)')
    data = TextField()
    Extra = StringField(ddl='varchar(255)')
    lasttime = StringField(ddl='varchar(255)')
    preview = StringField(ddl='varchar(255)')
    authority = IntegerField()
    mytype = IntegerField()

    @classmethod
    async def findproject(cls, **kw):
        escaped_fields = list(map(lambda f: '`%s`' % f, cls.__fields__))
        if not kw.get('isdata', False):
            escaped_fields.remove('`data`')
        else:
            kw.pop('isdata')

        indexlist = list(kw.keys())
        valuelist = list(kw.values())

        selectsql = 'select `%s`, %s from `%s`' % (cls.__primary_key__, ', '.join(escaped_fields), cls.__table__)
        sql = '%s where %s' % (selectsql, ' and '.join("`%s`=?" % argv for argv in indexlist))
        rs = await select(sql, valuelist)
        if len(rs) == 0:
            return None
        return [cls(**r) for r in rs]

    @classmethod
    async def updateproject(self, data={}, **kw):
        if data:

            indexlist = list(data.keys())
            updatesql = 'update `%s` set %s' % (self.__table__, ' , '.join("`%s`=?" % argv for argv in indexlist))
            argvs = list(data.values())
            sql = '%s where %s' % (updatesql, ' and '.join("`%s`=?" % argv for argv in list(kw.keys())))
            argvs.extend(list(kw.values()))
            rows = await execute(sql, argvs)
            if rows != 1:
                logger.warning('failed to update by primary key: affected rows: %s' % rows)
                return False
            return True

    @classmethod
    async def findpublic(cls, userid, qdsoftid):
        escaped_fields = list(map(lambda f: '`%s`' % f, cls.__fields__))
        escaped_fields.remove('`data`')

        sql = "select `%s`, %s " % (cls.__primary_key__, ', '.join(escaped_fields)) + \
              "from `quickdraw_software_project` where `userid` !=%s and `authority` = '2' and `qdsoftid`=%s"

        argvs = [userid, qdsoftid]
        rs = await select(sql, argvs)
        return [cls(**r) for r in rs]

    @classmethod
    async def findprojectandproductdata(cls, **kw):

        datajson = {}  # 返回的json结构
        projectdata = {}

        alldatalist = await cls.findproject(**kw)
        if alldatalist is None: return
        for data in alldatalist:
            projectdata = data

        productlist = []
        if 'guid' in projectdata:  # proguidadddeleteflag
            sql = "select * from quickdraw_software_product where project_guid=%s and deleteflag=0"
            productlist = await select(sql, [projectdata['guid']])
            productlist = ProductVO.resultvo(productlist)
        projectdata = ProjectVO.resultvo(projectdata)
        datajson['project'] = projectdata
        datajson['products'] = productlist
        return datajson

    @classmethod
    async def updateprojectandproduct(self, data={}, **kw):
        project = data['project']
        products = data['products']
        guid = project['guid']

        # state = Product.deleteproducts(guid)
        # if state:
        # self.addproducts(QdSoftProdata, products)
        nums = await self.findNumber(selectField = "count(*)",where="guid = '%s'"%(project.get('guid', '')))
        logger.info('nums={}'.format(nums))
        if nums !=1:
        #if kw.get('isinsert', False):
            logger.info('insert project')
            #project['data'] = quote(project['data'], 'utf-8')
            project = Project(qdsoftid=project.get('qdsoftid', ''),
                              userid=project.get('userid', ''),
                              guid=project.get('guid', ''),
                              sNo=project.get('sNo', ''),
                              sName=project.get('sName', ''),
                              sDes=project.get('sDes', ''),
                              data=project.get('data', ''),
                              Extra=project.get('Extra', ''),
                              preview=project.get('preview', ''),
                              lasttime = MyUtil.gettimestr())
            status = await project.save()
            guid = project.guid
        else:
            #project['data'] = quote(project['data'], 'utf-8')
            logger.info('update project')
            project.pop('time')
            project['lasttime'] = MyUtil.gettimestr()
            status = await self.updateproject(data=project, guid=guid)
        if status:
            await Product.delete('project_guid', guid)
            savelist = []
            for productdata in products:
                savelist.append(guid)
                savelist.append(productdata.get('guid', ''))
                savelist.append(productdata.get('sNo', ''))
                savelist.append(productdata.get('sName', ''))
                savelist.append(productdata.get('sDes', ''))
                savelist.append(productdata.get('data', ''))
                savelist.append(productdata.get('Extra', ''))
                savelist.append(0)
                savelist.append(0)
            product = Product()
            logger.info('insert all products')
            await product.saves(len(products), savelist)
            return project
        else:
            return False

class Product(Model):
    __table__ = 'quickdraw_software_product'
    id = IntegerField(primary_key=True)
    project_guid = StringField(ddl='varchar(255)')
    guid = StringField(ddl='varchar(255)')

    sNo = StringField(ddl='varchar(255)')
    sName = StringField(ddl='varchar(255)')
    sDes = StringField(ddl='varchar(255)')
    data = TextField()
    Extra = StringField(ddl='varchar(255)')
    deleteflag = IntegerField()

    @classmethod
    async def updateproduct(self, data={}, **kw):
        if data:
            indexlist = list(data.keys())
            updatesql = 'update `%s` set %s'%(self.__table__, ' , '.join("`%s`=?" % argv for argv in indexlist))
            argvs = list(data.values())
            sql = '%s where %s' % (updatesql,' and '.join("`%s`=?" % argv for argv in list(kw.keys())))
            argvs.extend(list(kw.values()))
            rows = await execute(sql, argvs)
            if rows != 1:
                logger.warning('failed to update by primary key: affected rows: %s' % rows)

class Room(Model):
    __table__ = 'quickdraw_software_room'
    id = IntegerField(primary_key=True)
    qdsoftid = StringField(ddl='varchar(255)')
    userid = StringField(ddl='varchar(255)')
    guid = StringField(ddl='varchar(255)')
    sName = StringField(ddl='varchar(255)')
    sDes = StringField(ddl='varchar(255)')
    data = TextField()
    preview = StringField(ddl='varchar(255)')
    isstore = IntegerField()

    @classmethod
    async def deleteroom(cls, indexname, guid):

        sql = "DELETE FROM `quickdraw_software_roomlibrary` where " \
              "roomid=(select quickdraw_software_room.id from `quickdraw_software_room` where `guid`=%s) " \
              "; DELETE FROM  `quickdraw_software_room` where `guid`=%s"

        rows = await execute(sql, [guid, guid])
        if rows != 1:
            logger.warning('failed to delete by {}: affected rows: {}'.format(indexname, rows))

    @classmethod
    async def findrooms(cls, **kw):
        indexlist = list(kw.keys())
        valuelist = list(kw.values())
        if 'id' in indexlist:
            sql = "select quickdraw_software_room.* , " \
                  "(select quickdraw_software_roomlibrary.id from quickdraw_software_roomlibrary " \
                  "where quickdraw_software_roomlibrary.roomid=quickdraw_software_room.id)as libraryid from quickdraw_software_room where " \
                  "quickdraw_software_room.id=%s"

        elif 'qdsoftid' in indexlist and 'userid' in indexlist:
            sql = "select id, qdsoftid,userid,guid,sName,sDes,preview,isstore, " \
                  "(select quickdraw_software_roomlibrary.id from quickdraw_software_roomlibrary " \
                  "where quickdraw_software_roomlibrary.roomid=quickdraw_software_room.id) as libraryid " \
                  "from quickdraw_software_room where " \
                  "userid=%s and quickdraw_software_room.qdsoftid=%s"

        elif 'qdsoftid' in indexlist:

            sql = "select id, qdsoftid,userid,guid,sName,sDes,preview,isstore, " \
                  "(select quickdraw_software_roomlibrary.id from quickdraw_software_roomlibrary " \
                  "where quickdraw_software_roomlibrary.roomid=quickdraw_software_room.id)as libraryid from quickdraw_software_room where " \
                  "quickdraw_software_room.qdsoftid=%s"
        rs = await select(sql, valuelist)
        if len(rs) == 0:
            return None
        return [cls(**r) for r in rs]

class RoomLibrary(Model):
    __table__ = 'quickdraw_software_roomlibrary'
    id = IntegerField(primary_key=True)
    roomid = StringField(ddl='varchar(255)')
    label = StringField(ddl='varchar(255)')
    roomnums = StringField(ddl='varchar(32)')
    area = StringField(ddl='varchar(255)')
    address = StringField(ddl='varchar(255)')
    propertyname = StringField(ddl='varchar(255)')

    @classmethod
    async def deleteroom(cls, indexname, id):

        sql = "UPDATE quickdraw_software_room set isstore = 0 where quickdraw_software_room.id = " \
              "(select roomid from quickdraw_software_roomlibrary where quickdraw_software_roomlibrary.id =%s);" \
              "DELETE FROM  quickdraw_software_roomlibrary where id =%s;"

        rows = await execute(sql, [id, id])
        if rows != 1:
            logger.warning('failed to delete by {}: affected rows: {}'.format(indexname, rows))


    @classmethod
    async def findroomlibrary(cls, **kw):

        valuelist = list(kw.values())

        sql = "select quickdraw_software_roomlibrary.*,quickdraw_software_room.sName as sName,quickdraw_software_room.preview as preview," \
              "quickdraw_software_room.data as data from quickdraw_software_roomlibrary, " \
              "quickdraw_software_room where quickdraw_software_room.id = quickdraw_software_roomlibrary.roomid and " \
              "quickdraw_software_roomlibrary.id = %s"
        rs = await select(sql, valuelist)
        if len(rs) == 0:
            return None
        return [cls(**r) for r in rs]